package com.saianfu.common.utils

import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs

object TimeUtil {
    const val y4m2d2 = "yyyy-MM-dd"
    const val y4m2d2h2m2s2 = "yyyy-MM-dd HH:mm:ss"

    /**
     * 根据毫秒值获取格式化的日期
     */
    fun timeFormatY4m2d2(timeMills: Long): String {
        return timeFormat(timeMills, y4m2d2)
    }

    /**
     * 根据毫秒值获取格式化的日期
     */
    fun timeFormatY4m2d2h2m2s2(timeMills: Long): String {
        return timeFormat(timeMills, y4m2d2h2m2s2)
    }

    /**
     * 根据毫秒值获取格式化的日期
     */
    fun timeFormat(timeMills: Long, format: String): String {
        val sdf = SimpleDateFormat(format)
        return sdf.format(timeMills)
    }

    /**
     * 根据格式化的日期获取毫秒值
     */
    fun timeMills(dateText: String, format: String): Long? {
        date(dateText, format)?.let {
            return it.time
        }
        return null
    }

    /**
     * 根据格式化的日期实例Date
     */
    fun date(dateText: String, format: String): Date? {
        val sdf = SimpleDateFormat(format)
        return try {
            sdf.parse(dateText)
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 根据两个日期的毫秒插值，获取两个日期之间相差多少个单位的天、小时、分钟、秒、毫秒
     */
    fun timeSpan(mills: Long, precision: Int): String {
        val unitMills = listOf(86400000, 3600000, 60000, 1000, 1)
        val unit = listOf("天", "小时", "分钟", "秒", "毫秒")
        if (mills == 0L) return "0" + unit.last()
        if (precision !in 0..4) {
            return ""
        }
        val builder = StringBuilder()
        var tempMills = abs(mills)
        for (index in 0..precision) {
            if (tempMills >= unitMills[index]) {
                val count = tempMills / unitMills[index]
                tempMills = mills % unitMills[index]
                builder.append(count.toString()).append(unit[index])
                if (tempMills == 0L) break
            }
        }
        return builder.toString()
    }

}